package cn.wolfcode.wolf2w.controller;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.domain.Visit;
import cn.wolfcode.wolf2w.redis.service.IVisitRedisService;
import cn.wolfcode.wolf2w.service.IVisitService;
import cn.wolfcode.wolf2w.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("visits")
public class VisitController {
    @Autowired
    private IVisitService visitService;
    @Autowired
    private IVisitRedisService visitRedisService;
    @GetMapping("visit")
    public Object visit(String id, @UserParam UserInfo userInfo){
        //调用Visit服务层的方法,将列表加入
        Visit visit = visitService.visit(id, userInfo);
        //调用VisitRedis层方法,更新总访问量和今日访问量
        visitRedisService.updateView(visit,userInfo.getId());
        //最后，将所有数据封装为map集合返回
        Map<String,Object> map=new HashMap<>();
        Collections.reverse(visit.getVisitors());
        map.put("totalView", visit.getTotalView());
        map.put("todayView", visit.getTodayView());
        return JsonResult.success(map);
    }
    @GetMapping("get")
    public Object get(String id, @UserParam UserInfo userInfo){
        //获取访客id
        Visit visit = visitService.getByOwnId(id);
        //将访客id加到记号中
        visitRedisService.setView(visit);

        Map<String,Object> map=new HashMap<>();
        map.put("totalView", visit.getTotalView());
        map.put("todayView", visit.getTodayView());
        Collections.reverse(visit.getVisitors());
        map.put("visitors",visit.getVisitors());
        return JsonResult.success(map);
    }
}
